
const BULLET_IMG_URL = 'images/plane/bullet.png';
const BULLET_POOL_NAME = 'BULLET_POOL';

define([
  'require', 'pool'
], function (require, pool) {
  'use strict';

  var _this = {};

  function init (app, container) {
    var self = _this;
    self.bulletArr = [];
    self.container = container;
    self.loading = true;

    new PIXI.loaders.Loader()
      .add('bulletImg', BULLET_IMG_URL)
      .load(function (loader, res) {
        self.bulletTex = PIXI.Texture.from('bulletImg');
        self.bulletSpeed = 10;
        
        // 先初始化10个
        for (let i = 0; i < 10; i++) {
          var bullet = newBullet()
          container.addChild(bullet);
          pool.put(BULLET_POOL_NAME, bullet);
          self.bulletArr.push(bullet);
        }
        self.loading = false;
      });
  }

  function update (delta) {
    if (_this.loading) return;
    _this.bulletArr.forEach(function (b, index, arr) {
      if (!b.visible) {
        return;
      }

      b.position.y -= _this.bulletSpeed * delta;
      if (b.position.y <= -b.height) {
        b.visible = false;
        pool.put(BULLET_POOL_NAME, b);
      }
    });
  }

  function fire (pos) {
    var bullet = pool.get(BULLET_POOL_NAME);
    if (bullet == null) {
      bullet = newBullet();
      _this.container.addChild(bullet);
      _this.bulletArr.push(bullet);
    }

    bullet.position.x = pos.x;
    bullet.position.y = pos.y;
    bullet.visible = true;
  }

  function newBullet() {
    var b = new PIXI.Sprite(_this.bulletTex);
    b.visible = false;
    b.scale.set(0.3);
    b.anchor.set(0.5);
    return b;
  }

  function recoverBullet (bullet) {
    bullet.visible = false;
    pool.put(BULLET_POOL_NAME, bullet);
  }

  return {
    init: init,
    update: update,
    fireAt: fire,
    recoverBullet: recoverBullet,
    data: _this,
  };

});